package com.example.demo.shior;

import java.util.HashSet;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class MyShiroRealm extends AuthorizingRealm {

	/**
	 * 授权
	 */
	/* (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		System.out.println("授权");
		
		
		String  primaryPrincipal = (String) principals.getPrimaryPrincipal();
		System.out.println(primaryPrincipal);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		HashSet<String> set = new HashSet<String>();
		set.add("true1");
		//第二种
		info.setStringPermissions(set);
		//第一种
		//info.addStringPermission("user:add");
		HashSet<String> set1 = new HashSet<String>();
		set1.add("admin");
		info.setRoles(set1);
		return null;
	}

	/**
	 * 认证
	 */
	@SuppressWarnings("unused")
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token1) throws AuthenticationException {
		System.out.println("认证");
		UsernamePasswordToken token = (UsernamePasswordToken) token1;
		System.out.println(token.getUsername());
		System.out.println(token.getPassword());
		//数据库值
		String username="zhangsan";
		String password="123456";
		System.out.println(getName());
		if(username.equals(token.getUsername())) {
			System.out.println("用户存在");
			if(password.equals(token.getPassword())) {
				System.out.println("密码正确");
				return new SimpleAuthenticationInfo(token.getUsername(), token.getPassword(), getName());
			}
			System.out.println("密码错误");
			//shior判断用户不存在 返回null ,就会抛出异常UnknownAccountException
			return null;
		}
		System.out.println("用户不存在");
		if (null== null) {
			return null;
		}
		if (token != null) {
			//shior根据token.getPassword()和页面输入的密码比较，不同惠抛出异常IncorrectCredentialsException
			return new SimpleAuthenticationInfo(token.getUsername(), token.getPassword(), getName());
		}
		return null;
	}

}
